<template>
  <el-card style="width: 100%; height: 100%">
    <div>
      <Category :isShow="isShow"></Category>
      <div v-if="isShow == 0">
        <el-card style="margin: 10px 0px">
          <el-button
            type="primary"
            icon="Plus"
            size="large"
            @click="addAttr"
            :disabled="!(CategoryStore.c3Id ? true : false)"
            v-has="`btn.Attr.add`"
            >添加平台属性</el-button
          >
          <el-table border style="margin: 10px 0px" :data="attrArr">
            <el-table-column
              label="序号"
              width="80px"
              align="center"
              type="index"
            ></el-table-column>
            <el-table-column
              label="属性名称"
              width="120px"
              prop="attrName"
            ></el-table-column>
            <el-table-column label="属性值名称">
              <template #="{ row }">
                <el-tag
                  v-for="item in row.attrValueList"
                  :key="item.attrId"
                  style="margin: 0px 5px"
                  >{{ item.valueName }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120px">
              <template #="{ row }">
                <el-button
                  type="primary"
                  icon="Edit"
                  size="small"
                  @click="changeAttr(row)"
                  v-has="`btn.Attr.update`"
                ></el-button>

                <el-popconfirm
                  :title="`是否删除${row.attrName}?`"
                  @confirm="deleteAttrList(row)"
                >
                  <template #reference>
                    <el-button
                      type="danger"
                      icon="delete"
                      size="small"
                      v-has="`btn.Attr.remove`"
                    ></el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
      <div v-else>
        <el-card style="margin: 10px 0px">
          <el-form inline>
            <el-form-item label="属性名称:">
              <el-input
                placeholder="请输入属性的名称"
                width="60%"
                v-model="attr.attrName"
              ></el-input>
            </el-form-item>
          </el-form>
          <el-button
            type="primary"
            icon="Plus"
            :disabled="attr.attrName ? false : true"
            @click="addAttrList"
            >添加属性值</el-button
          >
          <el-button>取消</el-button>
          <el-table border style="margin: 15px 0px" :data="attr.attrValueList">
            <el-table-column
              label="序号"
              type="index"
              width="80px"
              align="center"
            ></el-table-column>
            <el-table-column label="属性值">
              <template #="{ row, $index }">
                <el-input
                  v-if="row.flag"
                  v-model="row.valueName"
                  placeholder="请输入"
                  @blur="toLook(row, $index)"
                  :ref="(vc: any) => (inPutArr[$index] = vc)"
                ></el-input>
                <div v-else @click="toEdit(row, $index)">
                  {{ row.valueName }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #="{ $index }">
                <el-button
                  type="primary"
                  size="small"
                  icon="delete"
                  @click="attr.attrValueList.splice($index, 1)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            type="primary"
            @click="save"
            :disabled="attr.attrValueList.length == 0 ? true : false"
            >保存</el-button
          >
          <el-button @click="cancel">取消</el-button>
        </el-card>
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
//引入组合式API
import { watch, ref, reactive, nextTick, onBeforeUnmount } from "vue";
//引入封装好的接口
import { getDataList, addOrUpdateAttr, deleteAttr } from "@/api/produck/attr";
//引入数据类型
import type { AttrResponesData, AttrList, Attr } from "@/api/produck/attr/type";
//引入分类小仓库
import useCategoryStore from "@/store/modules/Category";
import { ElMessage } from "element-plus";
//获取数据
let CategoryStore = useCategoryStore();
//定义一个对象，收集数据
let attr = reactive<Attr>({
  attrName: "", //添加属性的名称
  attrValueList: [], //收集的数据
  categoryId: "", //三级类型id
  categoryLevel: 3, //代表三级id
});
//定义一个数组接收返回的data数据
let attrArr = ref<AttrList>([]);
//定义一个变量，接收input的vc实例
let inPutArr = ref<any>([]);
//定义一个变量，来控制cart组件的切换与隐藏
let isShow = ref(0);
//监视仓库数据，如果c3Id发生改变，则调用函数
watch(
  () => CategoryStore.c3Id,
  () => {
    //c3Id发生变化时，清空上一次的数据
    attrArr.value = [];
    //判断是否有c3Id,如果没有，则不执行
    if (CategoryStore.c3Id == "") {
      return;
    }
    DataList();
  },
);
//获取页面数据
const DataList = async () => {
  //先解构出c1Id,c2Id,c3Id
  const { c1Id, c2Id, c3Id } = CategoryStore;
  //调用接口，传入c1Id,c2Id,c3Id
  const result: AttrResponesData = await getDataList(c1Id, c2Id, c3Id);
  if (result.code == 200) {
    attrArr.value = result.data;
  }
};
//添加品牌属性按钮回调
const addAttr = () => {
  //控制card组件的切换
  isShow.value = 1;
  //清除上一次的数据
  attr.attrName = "";
  attr.attrValueList = [];
  attr.categoryId = "";
  //收集三级id
  attr.categoryId = CategoryStore.c3Id;
};
//修改品牌属性按钮回调
const changeAttr = (row: Attr) => {
  isShow.value = 1;
  //合并attr和row(使用深拷贝)
  Object.assign(attr, JSON.parse(JSON.stringify(row)));
};
//取消按钮的回调
const cancel = () => {
  isShow.value = 0;
};
//添加属性的回调函数
const addAttrList = () => {
  //用户点击按钮，就向数组添加一个对象
  attr.attrValueList.push({
    valueName: "",
    flag: true, //编辑与查看的切换
  });
  //等待组件加载完毕后获取焦点
  nextTick(() => {
    //获取焦点
    inPutArr.value[attr.attrValueList.length - 1].focus();
  });
};
//保存按钮回调
const save = async () => {
  //判断attr.valueList数据是否为空
  let reapet = attr.attrValueList.filter((item) => {
    //返回数据为空的数组
    return item.valueName == "";
  });
  if (reapet.length > 0) {
    ElMessage({
      type: "error",
      message: "属性值不能为空",
    });
    return;
  }
  //发请求
  let result = await addOrUpdateAttr(attr);
  if (result.code == 200) {
    //提示
    ElMessage({
      type: "success",
      message: attr.id ? "修改成功" : "添加成功",
    });
    //切换页面
    isShow.value = 0;
    //获取数据
    DataList();
  } else {
    ElMessage({
      type: "error",
      message: attr.id ? "修改失败" : "添加失败",
    });
  }
};
//文本框失去焦点的回调
const toLook = (row: any, index: number) => {
  //判断用户输入的文本是否为空，如果是空的就不在执行后面的语句，同时将数组中空的数组删除
  if (row.valueName.trim() == "") {
    ElMessage({
      type: "error",
      message: "输入的文本不能为空",
    });
    //通过index索引值删除数组中的数据
    attr.attrValueList.splice(index, 1);

    return;
  }
  //判断attr.attrValueList数组中是否有重复的数据使用find方法
  let isRepeat = attr.attrValueList.find((item) => {
    //判断item是否和当前的row相等
    if (item != row) {
      //返回一个有重复值的数组
      return item.valueName == row.valueName;
    }
  });
  if (isRepeat) {
    ElMessage({
      type: "warning",
      message: "属性值不能重复",
    });
    return;
  }

  //切换文本模式
  row.flag = false;
};
//切换为编辑模式
const toEdit = (row: any, index: number) => {
  row.flag = true;
  //等待组件加载完毕后获取焦点
  nextTick(() => {
    //获取焦点
    inPutArr.value[index].focus();
  });
};
//删除属性值
const deleteAttrList = async (row: any) => {
  let result = await deleteAttr(row.id);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  } else {
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
  //删除后再次获取数据
  DataList();
};
//组件销毁之前清除小仓库的数据
onBeforeUnmount(() => {
  //清除仓库数据
  CategoryStore.$reset();
});
</script>
